<?php 
/**
 *  index.php API 入口
 *
 * @copyright			(C) 2005-2010 PHPCMS
 * @license				http://www.phpcms.cn/license/
 * @lastmodify			2010-7-26
 */
define('PHPCMS_PATH', __DIR__.'/');
include PHPCMS_PATH.'phpcms/base.php';
$param = pc_base::load_sys_class('param');

/**
 * 自动抓取开关
 */
$settingDb = pc_base::load_model('epaper_setting_model');
$one = $settingDb->get_one(['name'=>'自动抓取']);
if(!$one || $one['value'] != 'true')
    return;

/**
 * 网页抓取最后一页的数字报
 */

function getDate2():array{

    // 跳过ssl验证
    $stream_opts = [
        "ssl" => [
            "verify_peer"=>false,
            "verify_peer_name"=>false,
        ]
    ];

    $publish_href = '';
    $publish_date = '';

    $url = 'https://www.chinaluan.com/lakblm_1';
    $content = file_get_contents($url,false, stream_context_create($stream_opts));
    if(!$content)
        throw new Exception("抓取首页失败");
    
    $xmlDoc = new DOMDocument();
    libxml_use_internal_errors(true);
    $xmlDoc->loadHTML($content);
    libxml_use_internal_errors(false);
    
    $xmlDoc->preserveWhiteSpace=false; 
    
    // bzlist2
    $xpath = new DOMXPath($xmlDoc);
    $elements = $xpath->query("/html/body//div[@class='bzlist2']//li/a");
    foreach($elements as $el){
        $href = $el->getAttribute('href');
        $title = $el->getAttribute('title');

        $h = explode("/",$href);

        if(!$h[2])
            throw new Exception('$h[2]解析失败！');
    
        $publish_href = $h[2];
        $publish_date = $title;

        break; // 改为只获取当天数据
    }
    
    // sort($publish_date);
    return [
        'href'=>$publish_href,
        'date'=>$publish_date
    ];
}

// grab("2023-01-01");

// delcache("publicsh_date","epaper");

$arr = getDate2();

$date = $arr['date'];
$href = $arr['href'];

if(!$date)
    die("arr:数据为空");

$epaper_upload_model = pc_base::load_model('epaper_upload_model');

// 只抓取最后一天数据
$date2 = date('Y-m-d', strtotime($date));
$one = $epaper_upload_model->get_one(['date'=>$date2]);
if($one){
    echo $date." skip\n";
    return;
}

sleep(2);
try{
    $id = $epaper_upload_model->grabAdd($href,$date2);
    $epaper_upload_model->analysisCfg($id);

}catch(Throwable $e){
    echo $date." 抓取失败\n".$e->getMessage()."\n";
}

